// pages/my/my.js
import { client } from '../../request/index.js'
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast'
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog'

Page({
  data: {
    navTop: getApp().globalData.navTop,
    imgIp: getApp().globalData.imgIp,
    isLogin: false,
    authPanelHidden: true,
    userId: '',
    dt_aCoin: 0,
    clock_times: 0,
    userType: '',
    popup_show: false,
    share_times: 0,
    share_act_times: 0,
  },
  // 显示授权登录框
  handleLogin() {
    this.setData({
      authPanelHidden: false,
    })
    getApp().globalData.showLoginDialog = false
  },
  // 点击授权按钮
  bindGetUserInfo: function (e) {
    let that = this
    if (e.detail.userInfo) {
      //允许授权
      that.login()
    } else {
      //拒绝授权
      Dialog.alert({
        title: '警告',
        message: '您拒绝了授权，请授权之后再使用 !',
      })
    }
    that.setData({
      authPanelHidden: true,
    })
    that.onLoad()
  },
  // 是否登录
  handleNav(url) {
    if (getApp().globalData.sessionid === '') {
      Toast('登录后才能使用哦~')
    } else {
      wx.navigateTo({
        url: url,
      })
    }
  },
  // 跳转助力记录
  todt() {
    this.handleNav('../dt_rec/dt_rec')
  },
  // 跳转打卡记录
  toClock() {
    this.handleNav('../account/clock_rec/clock_rec')
  },
  // 跳转用户反馈
  user_fb() {
    this.handleNav('../user_fb/user_fb')
  },
  //跳转商务合作
  comJoin() {
    this.handleNav('../cooperate/cooperate')
  },
  // 跳转账户明细
  account() {
    this.handleNav('../account/account')
  },
  // 跳转兑换记录
  exchange_list() {
    this.handleNav('../exchange_list/exchange_list')
  },
  // 跳转关注我们
  concern() {
    this.handleNav('../official/official')
  },
  // 跳转发布信息
  publish() {
    this.handleNav('../publish/publish')
  },
  // 跳转订单反馈
  order_fb() {
    this.handleNav('../order_fb/order_fb')
  },
  // 跳转用户手册
  help() {
    wx.navigateTo({
      url: '/pages/help/help',
    })
  },
  //跳转公益宣传
  topublicity() {
    this.handleNav('../publicity/publicity')
  },
  // 跳转个人信息
  toInfo() {
    this.handleNav('../info/info')
  },
  // 点击预约提醒
  subscribe_msg(e) {
    if (getApp().globalData.sessionid === '') {
      Toast('登录后才能使用哦~')
      return
    }
    wx.getSetting({
      withSubscriptions: true, //  这里设置为true,下面才会返回mainSwitch
      success: function (res) {
        // 调起授权界面弹窗
        if (res.subscriptionsSetting.mainSwitch) {
          // 用户打开了订阅消息总开关
          if (res.subscriptionsSetting.itemSettings != null) {
            // 用户同意总是保持是否推送消息的选择, 这里表示以后不会再拉起推送消息的授权
            let moIdState =
              res.subscriptionsSetting.itemSettings[
                'uKALq9eK4ZYnzLnC7MQgBv2oBa8seurRGe9pe-heFTg'
              ] // 用户同意的消息模板id
            if (moIdState === 'accept') {
              console.log('接受了消息推送')
              Dialog.alert({
                title: '预约提醒成功',
                message: '在12点和18点时将为您提供打卡提醒服务，记得打卡哦~',
              }).then(() => {
                // on close
              })
              console.log('总是同意')
            } else if (moIdState === 'reject') {
              console.log('拒绝消息推送')
              Dialog.alert({
                title: '您未允许发送订阅消息',
                message: '请在右上角三个点中的"设置/消息订阅"中允许发送消息',
              }).then(() => {
                // on close
              })
            } else if (moIdState === 'ban') {
              console.log('已被后台封禁')
            }
          } else {
            // 当用户没有点击 ’总是保持以上选择，不再询问‘  按钮。那每次执到这都会拉起授权弹窗
            Dialog.confirm({
              title: '提示',
              message: '是否授权开通服务通知',
              confirmButtonText: '是',
              cancelButtonText: '否',
            })
              .then(() => {
                wx.requestSubscribeMessage({
                  // 调起消息订阅界面
                  tmplIds: ['uKALq9eK4ZYnzLnC7MQgBv2oBa8seurRGe9pe-heFTg'],
                  success(res) {
                    console.log('订阅消息 成功 ')
                    console.log(res)
                    if (
                      res['uKALq9eK4ZYnzLnC7MQgBv2oBa8seurRGe9pe-heFTg'] ===
                      'accept'
                    ) {
                      Dialog.alert({
                        title: '预约提醒成功',
                        message:
                          '在12点和18点时将为您提供打卡提醒服务，记得打卡哦~',
                      }).then(() => {
                        // on close
                      })
                    } else {
                      Toast('您取消了预约提醒')
                    }
                  },
                  fail(er) {
                    console.log('订阅消息 失败 ')
                    console.log(er)
                  },
                })
              })
              .catch(() => {
                // on cancel
                Toast('您取消了预约提醒')
              })
          }
        } else {
          console.log('订阅消息未开启')
        }
      },
      fail: function (error) {
        console.log(error)
      },
    })
  },
  // 点击邀请好友
  showPopup() {
    this.setData({ popup_show: true })
  },
  // 关闭弹出框
  onClose() {
    this.setData({ popup_show: false })
  },
  // 提示分享朋友圈
  share_pyq() {
    Toast('Android用户请点击右上角的胶囊按钮进行分享(微信基础库 2.11.3 以上)')
  },
  // 获取分享次数
  async getShareTimes() {
    let that = this
    const mapData = await client({
      url: '/share/amounts',
      data: {
        user: that.data.userId,
      },
    })
    console.log('分享次数：', mapData)
    that.setData({
      share_times: mapData.data.data,
    })
  },
  // 生成邀请码
  async getInviteCode() {
    let that = this
    const mapData = await client({
      url: '/share/invitationcode',
      data: {
        user: that.data.userId,
      },
    })
    console.log('邀请码：', mapData)
    that.setData({
      in_code: mapData.data.data,
    })
  },
  // 跳转商家扫码
  scan() {
    let that = this
    wx.scanCode({
      onlyFromCamera: true,
      scanType: ['qrCode'],
      success(res) {
        console.log('scan:', res)
        let result = res.result
        wx.request({
          url:
            getApp().globalData.ip +
            '/exchangegoods/changeStatus?redeemcode=' +
            result +
            '&userId=' +
            that.data.userId,
          data: {},
          header: {
            'content-type': 'application/json',
            cookie: 'JSESSIONID=' + wx.getStorageSync('sessionid'),
          },
          method: 'POST',
          dataType: 'json',
          responseType: 'text',
          success: (res) => {
            console.log('/exchangegoods/changeStatus:', res)
            that.handleNav('../scan/scan' + '?message=' + res.data.message)
          },
        })
      },
    })
  },
  // 登录
  login() {
    let that = this
    wx.getUserInfo({
      success(u) {
        getApp().globalData.nickName = u.userInfo.nickName
        getApp().globalData.avatarUrl = u.userInfo.avatarUrl
        wx.login({
          success: (res) => {
            if (res.code) {
              wx.request({
                url: getApp().globalData.ip + '/login',
                data: {
                  code: res.code,
                  username: getApp().globalData.nickName,
                  headImg: getApp().globalData.avatarUrl,
                  invitaterId: getApp().globalData.invitaterId,
                },
                method: 'POST',
                header: {
                  'content-type': 'application/json;charset=utf-8',
                },
                dataType: 'json',
                success: (res1) => {
                  console.log('登录接口返回:', res1)
                  wx.setStorageSync('sessionid', res1.data.data.session)
                  getApp().globalData.sessionid = res1.data.data.session
                  getApp().globalData.roleName = res1.data.data.roleName
                  getApp().globalData.userType = res1.data.data.description
                  if (res1.statusCode == '200') {
                    console.log('登录成功！')
                    wx.setStorage({
                      key: 'guideOpen',
                      data: 2,
                    })
                    wx.setStorage({
                      key: 'clockGuideOpen',
                      data: false,
                    })
                    that.onLoad()
                    // onLoad()异步，跳转后首页要先使用userId, 此处单独获取
                    wx.request({
                      url: getApp().globalData.ip + '/account/detail',
                      header: {
                        'content-type': 'application/json',
                        cookie: 'JSESSIONID=' + wx.getStorageSync('sessionid'),
                      },
                      method: 'GET',
                      dataType: 'json',
                      responseType: 'text',
                      success: (res) => {
                        getApp().globalData.userId = res.data.data.userId
                        wx.switchTab({
                          url: '/pages/homepage/homepage',
                        })
                      },
                    })
                  } else {
                    //无网络
                    Dialog.alert({
                      title: '提示',
                      message: '请检查您的网络',
                    })
                  }
                },
                fail: () => {
                  console.log('发起登录请求失败！')
                },
              })
            } else {
              console.log('登录失败！' + res.errMsg)
            }
          },
        })
      },
    })
  },
  // 获取用户信息
  async initAccount() {
    let that = this
    const mapData = await client({
      url: '/account/detail',
    })
    console.log('用户信息:', mapData)
    getApp().globalData.userId = mapData.data.data.userId
    wx.setStorageSync('userId', mapData.data.data.userId)
    that.setData({
      userId: mapData.data.data.userId,
      isLogin: true,
      userType: getApp().globalData.userType,
    })
    that.getDaka()
    that.getACoin()
  },
  // 获取助力爱币
  async getACoin() {
    let that = this
    const mapData = await client({
      url: '/donate/donateaccount',
      data: {
        id: that.data.userId,
      },
    })
    console.log('助力爱币:', mapData)
    if (mapData.data.code === 200 && mapData.data.data) {
      this.setData({
        dt_aCoin: mapData.data.data,
      })
    }
  },
  // 获取打卡次数
  async getDaka() {
    const mapData = await client({
      url: '/account-log/clocklist',
    })
    console.log('打卡次数:', mapData)
    if (mapData.data.code == 888 || mapData.data.code == 500) {
      this.setData({
        clock_times: 0,
      })
    } else {
      this.setData({
        clock_times: mapData.data.data.length,
      })
    }
  },
  // 获取活动分享的次数
  async getNewYear() {
    let that = this
    const mapData = await client({
      url: '/share/newyearamounts',
      data: {
        id: that.data.userId,
      },
    })
    console.log('活动分享次数:', mapData)
    that.setData({
      share_act_times: mapData.data.data,
    })
  },

  onLoad(options) {
    let that = this
    if (getApp().globalData.sessionid !== '') {
      that.initAccount()
    }
  },

  onShow() {
    this.getDaka()
    this.getACoin()
    this.getShareTimes()
    this.getNewYear()
    if (getApp().globalData.showLoginDialog === true) {
      this.handleLogin()
    }
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline'],
    })
  },

  onPullDownRefresh() {
    this.onLoad()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  },

  onShareAppMessage(res) {
    let that = this
    if (res.from === 'button') {
      console.log('onShareAppMessage()==>>来自页面内转发按钮')
      console.log(res.target)
    } else {
      console.log('onShareAppMessage()==>>来自右上角转发菜单')
    }
    this.getInviteCode()
    return {
      title: '让光盘成为习惯，让爱心不断传递！',
      path: 'pages/homepage/homepage?invitaterId=' + that.data.userId,
      imageUrl: '../../images/share.png',
      success: function (res) {
        console.log('onShareAppMessage()==>>转发成功', res)
        //分享的是群还是个人
        getApp().setInfo(res)
      },
      fail: (res) => {
        console.log('onShareAppMessage()==>>转发失败', res)
      },
    }
  },

  onShareTimeline: function (res) {
    return {
      title: '让光盘成为习惯，让爱心不断传递！',
      imageUrl: '../../images/share.png',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      },
    }
  },
})
